
import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/keyboard_util.dart';
import 'package:baselib/utils/load_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/md5_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:baselib/utils/px_base_util.dart';
import 'package:baselib/utils/toast_util.dart';
import 'package:baselib/widgets/dialog_util.dart';
import 'package:flutter/material.dart';
import 'package:framelib/base/base_view_model.dart';
import 'package:framelib/config/api_config.dart';
import 'package:framelib/config/route_config.dart';
import 'package:framelib/net/baseentity.dart';
import 'package:framelib/utils/nim_sdk_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:module_business/module_comm/model/user_params_model.dart';
import 'package:module_business/module_index/model/index_room_item_entity.dart';
import 'package:module_business/module_index/model/voice_chat_tag_entity.dart';
import 'package:module_business/module_index/service/module_index_service.dart';
import 'package:module_business/module_index/view/create_voice_room_widget.dart';
import 'package:get/get.dart';

class IndexViewModel extends BaseViewModel<ModuleIndexService>{
  ModuleIndexService moduleIndexService;
  List<VoiceChatTagEntity> voiceChatTags = [];
  //被选中的tag下标
  int selectedTagIndex = 0;
  PageController pageController = PageController();
  //自己创建的房间
  IndexRoomItemEntity myRoomItemEntity=IndexRoomItemEntity();
  @override
  ModuleIndexService createService() =>moduleIndexService = ModuleIndexService();

  @override
  void onInit() {
    super.onInit();
    //获取标签列表
    getIndexTags();
    //查询我的房间
    getMyRoom();
  }
  @override
  void onClose() {
    if(pageController!=null)pageController.dispose();
    super.onClose();
  }
  void getIndexTags() async{
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_tag_list();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      List<VoiceChatTagEntity> results = baseEntity.result??[];
      if(results.isEmpty)return;
      var result = results[0];
      if(result==null)return;
      var tagChildrens = result.children??[];
      if(tagChildrens.isEmpty)return;
      voiceChatTags = tagChildrens;
      update();
    }
  }
  void getMyRoom() async{
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_queryMyRoom(parmsMap: {});
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      IndexRoomItemEntity results = baseEntity.result;
      if(results!=null){
        myRoomItemEntity = results;
        UserParamsModel.instance.setMyRoom(myRoomItemEntity);
        update();
      }
    }
  }

  tagItemClick(int index) {
    selectedTagIndex = index;
    pageController.animateToPage(selectedTagIndex,duration: Duration(milliseconds: 600),curve: Curves.easeInOutQuint);

  }

  onPageChanged(int pageIndex) {
    selectedTagIndex = pageIndex;
    update();
  }

  voiceRoomAdd() {
    if(myRoomItemEntity?.id==null){
      //添加房间
      DialogUtil.instance.showCommBottomSheet(
          child: CreateVoiceRoomWidget(
              onClose: ()=>NavigatorUtil.goBack(),
              onStart: (coverPath,roomName,roomPassword,roomTagId,roomRemark,isSetPassword){
                LogUtil.d('voiceRoomAdd-->coverPath=$coverPath\n,roomName=$roomName\n,'
                    'roomPassword=$roomPassword\n,roomTagId=$roomTagId\n,roomRemark=$roomRemark\n,isSetPassword=$isSetPassword');
                NavigatorUtil.goBack();
                //开始提交创建房间
                createRoom(coverPath,roomName,roomPassword,roomTagId,roomRemark,isSetPassword);
              }
          )
      );
    }else{
      //去我的房间
      toMyRoom();
    }
  }

  void createRoom(coverPath, roomName, roomPassword, roomTagId, roomRemark,isSetPassword) async{
    LoadUtil.showLoad(loadingText: StringUtil.instance.Creating);
    Map<String,dynamic> upData={
      'coverImg': coverPath,
      'password': (isSetPassword??false)?roomPassword:'',
      'roomName': roomName,
      'roomSynopsis': roomRemark,
      'tagId': roomTagId,
    };
    LogUtil.d('createRoom--->upData=$upData');
    // {coverImg: https://app-bucket-test.oss-accelerate.aliyuncs.com/ios/77985415/230314/u10233294541678777215792(960x1280).jpg, password: , roomName: tianqihao, roomSynopsis: nfjksansanjfs, tagId: 28}

    LoadUtil.hideLoad();
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_createRoom(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      ToastUtil.toast(StringUtil.instance.Create_success);
      //查询我的房间
      getMyRoom();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void toMyRoom() async{
    //api_voicechat_room_joinRoom
    LoadUtil.showLoad(loadingText: StringUtil.instance.data_loading);
    Map<String,dynamic> upData={
      'id': myRoomItemEntity?.id,
      'password': myRoomItemEntity?.password,
    };
    LogUtil.d('toMyRoom--->upData=$upData');
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_joinRoom(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      IndexRoomItemEntity roomItem = baseEntity?.result;
      //云信进入房间
      var  enterChatroomResult = await NIMSDKUtil.instance.enterChatroom(
        roomId: roomItem?.yxRoomId,
        nickname: UserParamsModel.instance.selfNIMUser.nick,
        avatar: UserParamsModel.instance.selfNIMUser.avatar
      );
      LoadUtil.hideLoad();
      if (enterChatroomResult.isSuccess) {
        LogUtil.d('进入聊天室成功');
        NavigatorUtil.pushByName(RouteConfig.myRoomPage,arguments: {
          'roomItem': roomItem
        });
      }else{
        LogUtil.d('进入聊天室失败');
      }
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }
}
